package com.exam.role.action;

import java.util.List;

import com.exam.base.action.BaseAction;
import com.exam.role.model.Module;
import com.exam.role.model.User;
import com.exam.role.service.LoginService;
import com.exam.role.service.RoleService;
import com.exam.util.Constants;

/**
 * 登录
 * 
 * @author huanghaijun
 * 
 */
public class LoginAction extends BaseAction {
	private RoleService roleService;
	private LoginService loginService;
	private User user;

	public LoginService getLoginService() {
		return loginService;
	}

	public void setLoginService(LoginService loginService) {
		this.loginService = loginService;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	/**
	 * 登录
	 * 
	 * @return
	 */
	public String login() {
		User user = loginService.getUser(this.user);
		if (null != user) {
			user.setUserType(this.user.getUserType());
			user.setMenus(roleService.getMenus(user.getRole().getId()));
			this.setAttribute(SESSION, Constants.CURRENT_USER, user);
		}
		return checkUser(user);
	}

	/**
	 * 退出登录
	 * 
	 * @return
	 */
	public String logout() {
		if (Constants.loginUser(getSession()) != null) {
			this.setAttribute(SESSION, Constants.CURRENT_USER, null);
		}
		getSession().invalidate();
		return INPUT;
	}

	/**
	 * 验证用户名、密码
	 * 
	 * @param user
	 * @return
	 */
	private String checkUser(User user) {
		if (null == user) {
			this.addFieldError("user.uname", "用户名不正确");
			return INPUT;
		} else if (!user.getPwd().equals(this.user.getPwd())) {
			this.addFieldError("user.pwd", "密码不正确");
			return INPUT;
		}
		return SUCCESS;
	}

	public RoleService getRoleService() {
		return roleService;
	}

	public void setRoleService(RoleService roleService) {
		this.roleService = roleService;
	}
}
